#include "Weather.h"
#include "GFuns.h"

Weather::Weather(EWeatherEffect aEffect)
{
	actualEffect = aEffect;
	drawer = NULL;
	isLightning = false;

	if(actualEffect == WEATHER_RAIN)
	{
		maxDrops = 3000;
		direction = randInterval(-PI/4,PI/4);
		minSpeed = 3;
		maxSpeed = 10;
		minLife = 50;
		maxLife = 200;
	}

	if(actualEffect == WEATHER_SNOW)
	{
		maxDrops = 1000;
		direction = randInterval(-PI/4,PI/4);
		minSpeed = 0.5;
		maxSpeed = 1;
		minLife = 300;
		maxLife = 1000;
	}

	for(unsigned int i=0; i<maxDrops; i++)
		AddDrop(true);
}

Weather::~Weather()
{
}

void Weather::AddDrop(bool aStarting)
{
	if(!drawer) return;

	Point pi = {randInterval(drawer->GetPanX()-drawer->GetScreenW()/2,drawer->GetPanX()+drawer->GetScreenW()*1.5),
								randInterval(drawer->GetPanY()-drawer->GetScreenH(),drawer->GetPanY()+drawer->GetScreenH())};
	RainDrop r(randInt(minLife,maxLife),pi,randInterval(minSpeed,maxSpeed),direction);

	if(aStarting) r.time = rand()%(r.life+1);
	drops.push_back(r);
}

void Weather::Tick()
{
	if(rand()%500 == 0)	isLightning = true;

	if(rand()%100 == 0)
	{
		direction += randInterval(-PI/32,PI/32);
		if(direction < -PI/4) direction = -PI/4;
		if(direction > PI/4) direction = PI/4;
	}

	for(unsigned int i=0; i<drops.size(); i++)
	{
		drops[i].time++;
		drops[i].position.x += drops[i].speed.x;
		drops[i].position.y += drops[i].speed.y;

		if(actualEffect == WEATHER_SNOW)
		{
			// from 1 to 0
			float scale = (drops[i].life - drops[i].time)/(float)drops[i].life;

			drops[i].width = scale*2.0 + 1;
		}

		if(drops[i].time > drops[i].life)
		{
			drops.erase(drops.begin() + i);
			i--;
		}
	}

	if(drops.size() < maxDrops)
	{
		int toAdd = maxDrops - drops.size();
		for(int i=0; i<toAdd; i++) AddDrop();
	}
}